<?php
/**
* 售后模块 工具类
*
* 售后模块 工具类的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Tool\Order;

use Illuminate\Support\Facades\Mail;
use App\Services\Tool\DataBase\SQL;
use Illuminate\Support\Facades\DB;
use Log, Auth;
use App\Services\Tool\GeneralTool;
use App\Services\UserService\UserTool;
use App\Services\ImgServices\ImgTool;
use App\Services\Tool\Order\OrderTool;
use App\Services\Tool\ExpressTool;
use App\Services\Tool\Jpush\JpushTool;

class AfterTool{

    function __construct(UserTool $userTool,
                         OrderTool $orderTool){
        $this->userTool        = $userTool;
        $this->orderTool       = $orderTool;

    }

    //售后列表
    function aftermark_lists($input){
        $lists = DB::table('order_aftermarks')
                 ->where(['user_id' => $input['user_id']])
                 ->orderBy('updated_at','desc')
                 ->select('order_after_id','order_id','type','state as after_state','created_at')
                 ->orderBy('updated_at','desc')
                 ->paginate($input['per_page'])
                 ->toArray();
        $lists['total_page'] = $lists['last_page'];

        foreach($lists['data'] as $list){
            $list->worksheet_id  = SQL::pluck(['table' => 'orders',
                                               'where' => ['order_id' => $list->order_id],
                                               'pluck' => 'worksheet_id']);
            $list->worksheet_id  = isset($list->worksheet_id) ? $list->worksheet_id : '';
            $list->enabled_worksheet  = SQL::pluck(['table' => 'orders',
                                               'where' => ['order_id' => $list->order_id],
                                               'pluck' => 'enabled_worksheet']);
            $list->enabled_worksheet  = isset($list->enabled_worksheet) ? $list->enabled_worksheet : '';
            $list->state_str = $this->get_after_state_str($list);
            $goods = $this->get_aftermark_detail($list);
            $list->good_total_quantity = $goods['good_total_quantity'];
            $list->goods = ['vaild' => $goods['vaild'],'unvaild'=>[]];
        }

        return $lists;
    }

    //申请售后
    function submit_aftermark($input){
        $state = 'M00003';
        try{
            $input['order_after_id'] = GeneralTool::only_no();
            //更改订单状态
            $order = $this->orderTool->order_submit_aftermark($input);
            if($order != 'M00000'){
                $state = $order;
                Throw new \Exception('售后更改订单状态异常');
            }
            //添加售后单
            $after = $this->order_aftermark($input);
            if($after != 'M00000'){
                $state = $after;
                Throw new \Exception('添加售后单异常');
            }
            $this->orderTool->submit_aftermark_success_push($input);
            return 'M00000';

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return $state;
        }finally{
            SQL::FinallyDo();
        }
    }

    //添加售后单操作
    function order_aftermark($input){
        //添加主表信息
        $after  = $this->insert_order_aftermak($input);
        if(!$after) return 'M05031';
        //添加详情
        $detail = $this->insert_order_after_detail($input);
        if($detail != 'M00000') return $detail;
        //添加图片
        $image  = $this->insert_order_aftermark_images($input);
        if($image != 'M00000') return $image;
        return 'M00000';
    }

    //填写退货单号
    function submit_order_aftermark_express($input){
        //判断物流单号是否符合长度
        if(preg_match('/^[0-9a-zA-Z]{10,16}$/',$input['order_express_id'])){
            if(!preg_match('/^[0-9]{10,16}$/',$input['order_express_id']))
                return 'M05037';
        }

        $express_name = $this->get_express_name_by_express_id($input['express_id']);
        if($express_name == '') return 'M05038';
        $state = 'M00003';
        try{
            $result = $this->insert_aftermark_express($input);
            if($result != 'M00000'){
                $state = $result;
                Throw new \Exception('填写退货单号异常');
            }
            return 'M00000';
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return $state;
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        获取售后单官方回寄物流信息
     */
    function get_aftermark_user_express($input){
        $result = $this->get_order_aftermark_info(['order_after_id' => $input['order_after_id'],
                                                   'user_id'        => $input['user_id']]);

        if(!isset($result) || !isset($result->send_express_id)) return (object)[];

        $result->express_name = $this->get_express_name_by_express_id($result->send_express_id);
        return $result;
    }

    /**
        售后单详情
     */
    function get_aftermark_detail_from_page($input, $type = 1){
        $where = [];
        if($type == 1) $where = ['user_id' => $input['user_id'], 'order_after_id' => $input['order_after_id']];
        if($type == 2) $where = ['order_after_id' => $input['order_after_id']];

        $result = $this->get_order_aftermark_info($where);
        if(!isset($result)) return (object)[];
        $result->after_state      = $result->state;
        $obj                      = (object)[];
        $obj->order_after_id      = isset($result->order_after_id) ? $result->order_after_id : '';
        $obj->order_id            = isset($result->order_id) ? $result->order_id : '';
        $obj->worksheet_id        = SQL::pluck(['table' => 'orders',
                                                'where' => ['order_id' => $result->order_id],
                                                'pluck' => 'worksheet_id']);
        $obj->worksheet_id        = isset($obj->worksheet_id) ? $obj->worksheet_id : '';
        $obj->enabled_worksheet   = SQL::pluck(['table' => 'orders',
                                                'where' => ['order_id' => $result->order_id],
                                                'pluck' => 'enabled_worksheet']);
        $obj->enabled_worksheet   = isset($obj->enabled_worksheet) ? $obj->enabled_worksheet : 0;
        $obj->title               = $this->get_after_state_str($result);
        $obj->title_message       = '';
        $obj->after_state         = $result->state;
        $obj->state               = $result->state;
        $obj->created_at          = $result->created_at;
        if($type == 2){
            $obj->order_id              = isset($result->order_id) ? $result->order_id : '';
            $obj->user_id               = isset($result->user_id) ? $result->user_id : '';
            $obj->state                 = isset($result->state) ? $result->state : '';
            $obj->created_at            = isset($result->created_at) ? $result->created_at : '';
            $obj->reason_desc           = isset($result->reason_desc) ? $result->reason_desc : '';
            $obj->result_desc           = isset($result->result_desc) ? $result->result_desc : '';
            $obj->express_id            = isset($result->express_id) ? $result->express_id : '';
            $obj->express_name          = ExpressTool::get_express_name_by_express_id($obj->express_id);
            $obj->order_express_id      = isset($result->order_express_id) ? $result->order_express_id : '';
            $obj->send_express_id       = isset($result->send_express_id) ? $result->send_express_id : '';
            $obj->send_order_express_id = isset($result->send_order_express_id) ? $result->send_order_express_id : '';
            $obj->send_order_express_id = isset($result->send_order_express_id) ? $result->send_order_express_id : '';
            $obj->back_remark           = isset($result->back_remark) ? $result->back_remark : '';
            $obj->rece                  = $this->orderTool->get_order_receiving($obj->order_id);
            $order                      = SQL::first(['table' => 'orders',
                                                      'where' => ['order_id' => $obj->order_id]]);
            $obj->pay_type              = isset($order->pay_type) ? $order->pay_type : '';
            $obj->trade_no              = isset($order->trade_no) ? $order->trade_no : '';
            $obj->total_fee             = isset($order->total_fee) ? $order->total_fee : '';
            $obj->total_price           = $this->orderTool->get_order_total_price($order->order_id);
            $obj->type                  = isset($result->type) ? $result->type : '';
            $obj->images                = $this->get_aftermark_images(['order_after_id' => $obj->order_after_id,
                                                                       'state' => 1]);
        }
        $goods                    = $this->get_aftermark_detail($result,$type);
        $obj->good_total_quantity = $goods['good_total_quantity'];
        $obj->goods               = ['vaild' => $goods['vaild'], 'unvaild' => []];
        $obj->process             = $this->get_order_aftermark_process($result);
        return $obj;
    }

    /**
        售后单确认收货
     */
    function order_aftermark_sign($input){
        $result = $this->get_order_aftermark_info(['user_id' => $input['user_id'], 'order_after_id' => $input['order_after_id'], 'state' => 6]);
        if(!isset($result)) return GeneralTool::createResult('','M05041');
        $input['order_id'] = $result->order_id;
        $update = $this->aftermark_sign_do($input);

        $arr = $update == 'M00000' ? $this->get_aftermark_detail_from_page($input) : '';
        if($update == 'M00000') $arr->state_str = $arr->title;
        return GeneralTool::createResult($arr,$update);
    }

    /**
     * 工具
     */
    /**
        获取售后图片数组
     */
    function get_aftermark_images($input){
        $images = SQL::get(['table' => 'order_after_images',
                            'where' => $input]);
        foreach($images as $img){
            $img->thumbnail      = env('IMG_URL_STD_PREFIX') . $img->thumbnail;
            $img->original_image = env('IMG_URL_STD_PREFIX') . $img->original_image;
        }
        return $images;
    }
    /**
        获取售后进度流程数组
     */
    function get_order_aftermark_process($result){
        $arr = [];
        if($result->state == 0 || $result->state >= 1) {
            $arr[] = (object)['title'   => '申请已提交，等待审核',
                              'message' => '',
                              'time_str'=> date('Y.m.d H:i',$result->created_at),
                              'time'    => $result->created_at];
        }

        if($result->state == 0){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_fail', 'time');
            $arr[] = (object)['title'   => '审核未通过',
                              'message' => isset($result->result_desc) && $result->result_desc != '' ? pack('H*',$result->result_desc) : '',
                              'time_str'=> date('Y.m.d H:i',$time),
                              'time'    => $time];
        }

        if($result->state > 1){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_pass', 'time');
            $arr[] = (object)['title'   => '审核通过',
                              'message' => isset($result->result_desc) && $result->result_desc != '' ? pack('H*',$result->result_desc) : '',
                              'time_str'=> is_numeric($time) ? date('Y.m.d H:i',$time) : '',
                              'time'    => is_numeric($time) ? $time : 0];
        }

        if($result->state > 2){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_user_send_back', 'time');
            $express_name = $this->get_express_name_by_express_id($result->express_id);
            $arr[] = (object)['title'   => '返货中',
                              'message' => '物流公司：' . $express_name . '\n物流单号：' . $result->order_express_id,
                              'time_str'=> is_numeric($time) ? date('Y.m.d H:i',$time) : '',
                              'time'    => is_numeric($time) ? $time : 0];
        }

        if($result->state > 3){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_backstage_sign', 'time');
            $arr[] = (object)['title'   => '官方已收货',
                              'message' => '核查属实，我们将在3个工作日内将换货寄出',
                              'time_str'=> is_numeric($time) ? date('Y.m.d H:i',$time) : '',
                              'time'    => is_numeric($time) ? $time : 0];
        }

        if($result->state > 4){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_backstage_in_process', 'time');
            $arr[] = (object)['title'   => '处理中',
                              'message' => '',
                              'time_str'=> is_numeric($time) ? date('Y.m.d H:i',$time) : '',
                              'time'    => is_numeric($time) ? $time : 0];
        }

        if($result->state > 5){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_backstage_send_back', 'time');
            $express_name = $this->get_express_name_by_express_id($result->send_express_id);
            $arr[] = (object)['title'   => '官方已将商品寄回，请注意查收',
                              'message' => '物流公司：' . $express_name . '\n物流单号：' . $result->send_order_express_id,
                              'time_str'=> is_numeric($time) ? date('Y.m.d H:i',$time) : '',
                              'time'    => is_numeric($time) ? $time : 0];
        }
        if($result->state > 6){
            $time  = $this->orderTool->get_order_operation_time($result->order_after_id, 'after_backstage_send_back', 'time');
            $express_name = $this->get_express_name_by_express_id($result->send_express_id);
            $arr[] = (object)['title'   => '买家已收货',
                              'message' => '',
                              'time_str'=> is_numeric($time) ? date('Y.m.d H:i',$time) : '',
                              'time'    => is_numeric($time) ? $time : 0];
        }

        $arr = $this->array_sort($arr);
        return $arr;
    }
    /**
        记录填写退货单号操作
     */
    function insert_aftermark_express($input){
        $result = SQL::update(['table' => 'order_aftermarks',
                               'where' => ['order_after_id' => $input['order_after_id'],
                                           'user_id'        => $input['user_id'],
                                           'state'          => 2],
                               'update'=> ['state'            => 3,
                                           'express_id'       => $input['express_id'],
                                           'order_express_id' => $input['order_express_id'],
                                           'updated_at'       => time()]]);

        if(!$result) return 'M00001';

        $operation = $this->orderTool->insert_order_operation(['iden'             => 1,
                                                               'user_id'          => $input['user_id'],
                                                               'order_after_id'   => $input['order_after_id'],
                                                               'after_state'      => 2,
                                                               'over_after_state' => 3]);

        return 'M00000';
    }
    /**
        记录用户售后单确认收货操作
     */
    function aftermark_sign_do($input){
        $state = 'M00001';
        try{
            $result = SQL::update(['table' => 'order_aftermarks',
                                   'where' => ['order_after_id' => $input['order_after_id'],
                                               'user_id'        => $input['user_id'],
                                               'state'          => 6],
                                   'update'=> ['state'            => 7,
                                               'updated_at'       => time()]]);

            if(!$result) Throw new \Exception('更新售后单状态失败');

            $order = SQL::update(['table' => 'orders',
                                   'where' => ['order_id' => $input['order_id'],
                                               'buyer_id' => $input['user_id'],
                                               'state'    => 4],
                                   'update'=> ['state'        => 4,
                                               'is_aftermark' => 0,
                                               'is_close'     => 1,
                                               'updated_at'   => time()]]);

            $operation = $this->orderTool->insert_order_operation(['iden'             => 1,
                                                                   'user_id'          => $input['user_id'],
                                                                   'order_id'         => $input['order_id'],
                                                                   'order_state'      => 4,
                                                                   'over_order_state' => 4,
                                                                   'order_after_id'   => $input['order_after_id'],
                                                                   'after_state'      => 6,
                                                                   'over_after_state' => 7,
                                                                   'is_close'         => 1]);
            OrderTool::deal_with_by_order_detail_fee(['order_id' => $input['order_id']]);
            if(!$operation) Throw new \Exception('记录订单操作记录失败');

            return 'M00000';
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return $state;
        }finally{
            SQL::FinallyDo();
        }
    }
    /**
        物流公司编号获取物流公司名称
     */
    function get_express_name_by_express_id($input){
        $express = SQL::pluck(['table' => 'express',
                               'where' => ['express_id' => $input],
                               'pluck' => 'express_name']);
        return isset($express) ? $express : '';
    }
    /**
        获取售后单详情
     */
    function get_aftermark_detail($after, $type = 1){
        $details = SQL::get(['table' => 'order_after_details',
                             'where' => ['order_after_id' => $after->order_after_id,
                                         'state'          => 1]]);

        $goods['good_total_quantity'] = 0;
        $goods['vaild'] = [];
        foreach($details as $det){
            $obj                        = $this->orderTool->get_order_detail_by_order_detail_number($det->order_detail_number);
            $arr['order_detail_number'] = isset($det->order_detail_number) ? $det->order_detail_number : '';
            $arr['product_id']          = isset($obj->product_id) ? $obj->product_id : '';
            $arr['product_temp_name']   = isset($obj->product_temp_name) ? $obj->product_temp_name : '';
            $arr['brand_name']          = isset($obj->brand_name) ? $obj->brand_name : '';
            $arr['colour_name']         = isset($obj->colour_name) ? $obj->colour_name : '';
            $arr['size_name']           = isset($obj->size_name) ? $obj->size_name : '';
            $arr['quantity']            = isset($det->quantity) ? $det->quantity : '';
            $arr['original_price']      = isset($obj->original_price) ? $obj->original_price : 0;
            $arr['preferential_price']  = isset($obj->preferential_price) ? $obj->preferential_price : 0;
            $arr['thumbnail'][]         = isset($obj->thumbnail) ? env('IMG_URL_STD_PREFIX') . $obj->thumbnail : '';
            $arr['original_image'][]    = isset($obj->original_image) ? env('IMG_URL_STD_PREFIX') . $obj->original_image : '';
            if($type == 1){
                $arr['gifts'] = [];
            }else if($type == 2){
                $arr['gifts'] = $this->orderTool->get_order_product_gift($arr,$after->order_id);
            }
            $arr['lists']                 = [];
            $goods['good_total_quantity'] += $det->quantity;
            $goods['vaild'][]             = (object)$arr;
        }
        return $goods;
    }

    /**
        获取售后状态字符串
     */
    function get_after_state_str($list, $type = 1){
        switch($list->after_state){
            case 0:
                return $type == 1 ? '审核未通过' : '审核未通过';
            case 1:
                return $type == 1 ? '审核中' : '申请已提交，等待审核';
            case 2:
                return $type == 1 ? '审核通过' : '审核通过';
            case 3:
                return $type == 1 ? '返货中' : '返货中';
            case 4:
                return $type == 1 ? '官方已收货' : '官方已收货';
            case 5:
                return $type == 1 ? '处理中' : '处理中';
            case 6:
                return $type == 1 ? '官方已寄回' : '官方已将商品寄回，请注意查收';
            case 7:
                return $type == 1 ? '买家已收货' : '买家已收货';
            default:
                return '';
        }
    }

    /**
        添加售后图片
     */
    function insert_order_aftermark_images($input){
        $images = json_decode($input['images'],true);
        $num  = 0;
        if(!isset($images) || !is_array($images) || count($images) < 1 || count($images) > 5)
            return 'M05029';
        foreach($images as $image){
            if(!isset($image['thumbnail']) || !isset($image['original_image']) || !is_string($image['thumbnail']) || !is_string($image['original_image']))
                return 'M05033';
            if(!ImgTool::imageUrlIsValid($image['thumbnail']) || !ImgTool::imageUrlIsValid($image['original_image']))
                return 'M05034';
            $arr['order_after_id'] = $input['order_after_id'];
            $arr['original_image'] = ImgTool::getImgPathByImgUrl($image['original_image']);
            $arr['thumbnail']      = ImgTool::getImgPathByImgUrl($image['thumbnail']);
            $arr['created_at']     = time();

            $insert = SQL::insert(['table'  => 'order_after_images',
                                   'insert' => $arr]);
            if($insert) $num++ ;
        }
        if(count($images) != $num) return 'M05035';
        return 'M00000';
    }

    /**
        添加售后详情
     */
    function insert_order_after_detail($input){
        $body = json_decode($input['body'],true);
        Log::info($body);
        $num  = 0;
        if(!isset($body) || !is_array($body) || count($body) == 0)
            return 'M05028';
        foreach($body as $one){
            if(!isset($one['order_detail_number']) || !isset($one['quantity']) || $one['quantity'] <= 0)
                return 'M05028';
            $detail = $this->orderTool->get_order_detail_by_order_detail_number($one['order_detail_number']);
            if(!isset($one['quantity']) || $one['quantity'] < $one['quantity'])
                return 'M05028';
            if($this->get_order_after_detail_count(['order_after_id'      => $input['order_after_id'],
                                                    'order_detail_number' => $one['order_detail_number'],
                                                    'state'               =>1]))
                return 'M05028';

            $arr['order_after_id']      = $input['order_after_id'];
            $arr['order_detail_number'] = $one['order_detail_number'];
            $arr['quantity']            = $one['quantity'];
            $arr['created_at']          = time();

            $insert = SQL::insert(['table'  => 'order_after_details',
                                   'insert' => $arr]);
            if($insert) $num++ ;
        }
        if(count($body) != $num) return 'M05032';
        return 'M00000';
    }

    /**
        添加售后主表
     */
    function insert_order_aftermak($input){
        $arr['order_after_id']        = $input['order_after_id'];
        $arr['order_id']              = $input['order_id'];
        $arr['user_id']               = $input['user_id'];
        $arr['type']                  = 2;
        $arr['reason_desc']           = isset($input['message']) && $input['message'] != '' ? bin2hex($input['message']) : '';
        $arr['result_desc']           = '';
        $arr['back_remark']           = '';
        $arr['express_id']            = '';
        $arr['order_express_id']      = '';
        $arr['send_express_id']       = '';
        $arr['send_order_express_id'] = '';
        $arr['created_at']            = time();
        $arr['updated_at']            = $arr['created_at'];

        $result = SQL::insert(['table'  => 'order_aftermarks',
                               'insert' => $arr]);
        return $result;
    }

    /**
        判断售后详情是否存在
     */
    function get_order_after_detail_count($input){
        $result = DB::table('order_after_details')
                  ->where($input)
                  ->whereIn('state',[1,2,3,4,5,6])
                  ->count();
        return $result;
    }

    /**
        判断售后单是否存在
     */
    function get_order_aftermark_count($input){
        $count = SQL::count(['table' => 'order_aftermarks',
                             'where' => $input]);
        return $count;
    }

    /**
         获取售后单信息
     */
    function get_order_aftermark_info($input){
        $result = SQL::first(['table' => 'order_aftermarks',
                              'where' => $input]);
        return $result;
    }

    /**
        获取售后商品数量
     */
    function get_order_aftermark_good_total_quantity($order_after_id){
        $lists = SQL::lists(['table' => 'order_after_details',
                             'where' => ['order_after_id' => $order_after_id,
                                         'state'          => 1],
                             'lists' => 'quantity']);
        return array_sum($lists);
    }
    /**
        获取售后单第一件商品图
     */
    function get_order_aftermark_first_picture($input, $type = 1){
        $result = DB::table('order_after_details')
                  ->where(['order_after_id' => $input,
                           'state'          => 1])
                  ->first();
        if(!isset($result)) [];

        $detail = DB::table('order_details')
                  ->where(['order_detail_number' => $result->order_detail_number])
                  ->select('thumbnail','original_image')
                  ->first();
        if($type == 2){
            $arr['original_image'][] = isset($detail->original_image) ? env('IMG_URL_STD_PREFIX') . $detail->original_image : '';
            $arr['thumbnail'][]      = isset($detail->thumbnail) ? env('IMG_URL_STD_PREFIX') . $detail->thumbnail : '';
        }else{
            $arr['original_image'][] = isset($detail->original_image) ? $detail->original_image : '';
            $arr['thumbnail'][]      = isset($detail->thumbnail) ? $detail->thumbnail : '';
        }
        return $arr;
    }

    /**
        数组倒序
     */
    function array_sort($arr){
        $ar    = [];
        $count = count($arr);
        for($a = 1; $a <= $count;$a++){
            if(isset($arr[$count - $a])) $ar[] = $arr[$count - $a];
        }
        return $ar;
    }

    /**
        获取用户售后单数量
     */
    function get_user_aftermark_number($input){
        $count = DB::table('order_aftermarks')
                 ->where(['user_id' => $input])
                 ->whereIn('state',[1,2,3,4,5,6])
                 ->count();
        return $count;
    }


    /**
        后台
     */
    /**
        售后列表
     */
    function aftermark_lists_backstage($input, $per_page = 10){
        $date_range_picker = isset($input['time_range'])?$input['time_range']:'01/01/2015 - 12/30/2025';

        $from_time = substr(trim($date_range_picker),0,strpos(trim($date_range_picker),'-')-1);
        $to_time   = substr(trim($date_range_picker),strpos(trim($date_range_picker),'-')+2);
        $from_time = strtotime($from_time.' 00:00:00') ? strtotime($from_time.' 00:00:00') : strtotime('01/01/2015'.' 00:00:00');
        $to_time   = strtotime($to_time.' 23:59:59') ? strtotime($to_time.' 23:59:59') : strtotime('12/30/2025'.' 00:00:00');
        if(isset($input['time_range'])) unset($input['time_range']);

        $afters = DB::table('order_aftermarks')
                  ->where($input)
                  ->whereBetween('created_at',[$from_time, $to_time])
                  ->orderBy('created_at','desc')
                  ->paginate($per_page);
        foreach($afters as $after){
            $after->rece = $this->orderTool->get_order_receiving($after->order_id);
            $order       = SQL::first(['table' => 'orders',
                                       'where' => ['order_id' => $after->order_id]]);
            $after->total_fee = isset($order->total_fee) ? $order->total_fee : '';
        }
        return $afters;
    }

    /**
        售后详情
     */
    function aftermark_detail($input){
        $after = $this->get_aftermark_detail_from_page($input, 2);
        return $after;
    }

    /**
        修改售后状态
     */
    function update_after_state($input){
        switch($input['state']){
            case 0:
                //审核未通过
                $arr['where']['order_after_id'] = $input['order_after_id'];
                $arr['where']['state']          = 1;
                $arr['update']['state']         = 0;
                $arr['update']['updated_at']    = time();
                $result = $this->update_after_state_tool($arr);
                if($result != 'M00000') return 'M05058';
                //push
                $this->aftermark_unpass_to_push($arr);
                return 'M00000';
            case 2:
                //审核通过
                $arr['where']['order_after_id'] = $input['order_after_id'];
                $arr['where']['state']          = 1;
                $arr['update']['state']         = 2;
                $arr['update']['updated_at']    = time();
                $result = $this->update_after_state_tool($arr);
                if($result != 'M00000') return 'M05058';
                //push
                $this->aftermark_pass_to_push($arr);
                return 'M00000';
            case 4:
                //官方已收获
                $arr['where']['order_after_id'] = $input['order_after_id'];
                $arr['where']['state']          = 3;
                $arr['update']['state']         = 4;
                $arr['update']['updated_at']    = time();
                $result = $this->update_after_state_tool($arr);
                if($result != 'M00000') return 'M05059';

                return 'M00000';
            case 5:
                //处理中
                $arr['where']['order_after_id'] = $input['order_after_id'];
                $arr['where']['state']          = 4;
                $arr['update']['state']         = 5;
                $arr['update']['updated_at']    = time();
                $result = $this->update_after_state_tool($arr);
                if($result != 'M00000') return 'M05060';
                //push
                $this->aftermark_dealing_to_push($arr);
                return 'M00000';
            case 6:
                //官方已寄回
                $arr['where']['order_after_id']         = $input['order_after_id'];
                $arr['where']['state']                  = 5;
                $arr['update']['send_express_id']       = $input['send_express_id'];
                $arr['update']['send_order_express_id'] = $input['send_order_express_id'];
                $arr['update']['state']                 = 6;
                $arr['update']['updated_at']            = time();
                $result                                 = $this->update_after_state_tool($arr);
                if($result != 'M00000') return 'M05061';
                //push
                $this->aftermark_resend_to_push($arr);
                return 'M00000';
            default:
                return 'M00004';
        }
    }

    /**
        售后单管理寄出商品
     */
    function system_resend_express($input){
        $express_name = ExpressTool::get_express_name_by_express_id($input['send_express_id']);
        if(!isset($express_name) || $express_name == '')
            return 'M05055';
        $input['state'] = 6;
        $result = $this->update_after_state($input);
        return $result;
    }

    /**
        工具
     */

    /**
        修改售后单通用方法
     */
    private function update_after_state_tool($input){

        SQL::FirstDo();
        $state = 'M00003';
        try{
            $update = SQL::update(['table' => 'order_aftermarks',
                                   'where' => $input['where'],
                                   'update'=> $input['update']]);
            if(!$update){
                $state = 'M00001';
                Throw new \Exception('修改售后单状态失败');
            }

            if($input['update']['state'] == 0 && $input['where']['state'] == 1){
                $order_id = SQL::pluck(['table' => 'order_aftermarks',
                                        'where' => ['order_after_id' => $input['where']['order_after_id']],
                                        'pluck' => 'order_id']);
                if(isset($order_id)){
                    SQL::update(['table' => 'orders',
                             'where' => ['order_id'     => $order_id,
                                         'is_aftermark' => 1],
                             'update'=> ['is_aftermark' => 0]]);
                }
            }

            $arr['order_after_id']   = $input['where']['order_after_id'];
            $arr['after_state']      = $input['where']['state'];
            $arr['over_after_state'] = $input['update']['state'];
            $arr['iden']             = isset($input['iden']) && $input['iden'] == 1? $input['iden'] : 0;
            $arr['user_id']          = $arr['iden'] == 1 && isset($input['user_id'])? $input['user_id'] : Auth::user()->id;
            $insert                  = OrderTool::insert_order_operation($arr);
            return 'M00000';
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return $state;
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        推送
     */
    /**
        审核未通过
     */
    private function aftermark_unpass_to_push($arr){
        try{
            $user_id    = $this->get_aftermark_user_id_by_order_after_id($arr['where']['order_after_id']);
            if(!isset($user_id) || $user_id == '' || $user_id == 0) return ;
            $images     = $this->get_aftermark_first_images($arr['where']['order_after_id']);
            $title      = '售后申请未通过';
            $message    = '【售后申请未通过】很抱歉，你的申请没能通过审核  >>查看详情';
            $message_in = '很抱歉，你的申请没能通过审核，点击查看原因';
            JpushTool::push($message,0,$user_id,['title'      => $title,
                                                 'user_id'    => $user_id,
                                                 'class'      => 'transaction_information',
                                                 'type'       => 5,
                                                 'jump_value' => $arr['where']['order_after_id'],
                                                 'template_no'=> '3',
                                                 'message'    => $message_in,
                                                 'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        审核通过
     */
    private function aftermark_pass_to_push($arr){
        try{
            $user_id    = $this->get_aftermark_user_id_by_order_after_id($arr['where']['order_after_id']);
            if(!isset($user_id) || $user_id == '' || $user_id == 0) return ;
            $images     = $this->get_aftermark_first_images($arr['where']['order_after_id']);
            $title      = '售后申请已通过';
            $message_in = '请将退换的商品寄回，点击查看详情';
            $message    = '【售后申请已通过】请将退换的商品寄回，待核实后为您重新发货  >>查看详情';
            JpushTool::push($message,0,$user_id,['title'      => $title,
                                                 'user_id'    => $user_id,
                                                 'class'      => 'transaction_information',
                                                 'type'       => 5,
                                                 'jump_value' => $arr['where']['order_after_id'],
                                                 'template_no'=> '3',
                                                 'message'    => $message_in,
                                                 'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        处理中
     */
    function aftermark_dealing_to_push($arr){
        try{
            $user_id    = $this->get_aftermark_user_id_by_order_after_id($arr['where']['order_after_id']);
            if(!isset($user_id) || $user_id == '' || $user_id == 0) return ;
            $images     = $this->get_aftermark_first_images($arr['where']['order_after_id']);
            $title      = '退换货已核实';
            $message    = '【售后申请已通过】退换货核查属实，我们将在三个工作日内为你重新发货 >>查看详情';
            $message_in = '退换货核查属实，我们将在三个工作日内为你重新发货';
            JpushTool::push($message,0,$user_id,['title'      => $title,
                                                 'user_id'    => $user_id,
                                                 'class'      => 'transaction_information',
                                                 'type'       => 5,
                                                 'jump_value' => $arr['where']['order_after_id'],
                                                 'template_no'=> '3',
                                                 'message'    => $message_in,
                                                 'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        官方已寄回
     */
    function aftermark_resend_to_push($arr){
        try{
            $user_id    = $this->get_aftermark_user_id_by_order_after_id($arr['where']['order_after_id']);
            if(!isset($user_id) || $user_id == '' || $user_id == 0) return ;
            $images      = $this->get_aftermark_first_images($arr['where']['order_after_id']);
            $title       = '退换商品已寄回';
            $message_in  = $image['product_temp_name'] . '已重新发货，运单编号：' .
                           $arr['update']['send_order_express_id'] . '  快递公司：'.
                           ExpressTool::get_express_name_by_express_id($arr['update']['send_order_express_id']) . '，请注意查收~';
            $message     = '【退换商品已寄回】' . $message_in;
            JpushTool::push($message,0,$user_id,['title'      => $title,
                                                 'user_id'    => $user_id,
                                                 'class'      => 'transaction_information',
                                                 'type'       => 6,
                                                 'jump_value' => $arr['where']['order_after_id'],
                                                 'template_no'=> '3',
                                                 'message'    => $message_in,
                                                 'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        修改售后单后台备注
     */
    function update_aftermark_back_remark($input){
        $result = SQL::update(['table' => 'order_aftermarks',
                               'where' => ['order_after_id' => $input['order_after_id']],
                               'update'=> ['back_remark'    => $input['back_remark']]]);
        return $result ? 'M00000' : 'M00001';
    }

    /**
        获取售后单打印图信息
     */
    function get_after_prints_to_zip($input){
        $after_details = SQL::get(['table' => 'order_after_details',
                                   'where' => ['order_after_id' => $input,
                                               'state'          => 1]]);

        $arr = [];
        foreach($after_details as $det){
            $detail = SQL::first(['table' => 'order_details',
                                  'where' => ['order_detail_number' => $det->order_detail_number]]);
            if(!isset($detail)) continue;
            $print = $this->orderTool->get_order_product_prints($detail, $detail->order_id);
            $arr[$det->order_detail_number.''] = $print;
        }
        return $arr;
    }

    /**
        工具
     */
    function get_aftermark_first_images($order_after_id){
        $after_detail = SQL::first(['table' => 'order_after_details',
                                    'where' => ['order_after_id' => $order_after_id,
                                                'state'          => 1]]);
        if(!isset($after_detail) || !isset($after_detail->order_detail_number)) return [];
        $detail = SQL::first(['table' => 'order_details',
                              'where'=> ['order_detail_number' => $after_detail->order_detail_number]]);

        $arr['thumbnail'] = isset($detail->thumbnail) ? $detail->thumbnail : '';
        $arr['original_image'] = isset($detail->original_image) ? $detail->original_image : '';
        $arr['product_temp_name'] = isset($detail->product_temp_name) ? $detail->product_temp_name : '';
        return $arr;
    }

    /**
        获取售后单用户编号
     */
    function get_aftermark_user_id_by_order_after_id($order_after_id){
        $user_id = SQL::pluck(['table' => 'order_aftermarks',
                               'where' => ['order_after_id' => $order_after_id],
                               'pluck' => 'user_id']);
        return isset($user_id)? $user_id : '';
    }

    /**
        定时
     */

    /**
        售后确认收货超时
     */
    static function command_order_aftermark_sign(){
        Log::info('----------售后确认收货超时处理开始----------');
        $order_after_time = OrderTool::get_data_from_configs(['name' => 'order_aftermark_unsign','state' => 1]);
        if(!isset($order_after_time) || !is_numeric($order_after_time)) return false;
        $end_time   = time() - $order_after_time;
        $orders = DB::table('order_aftermarks')
                  ->where(['state' => 6])
                  ->get();
        $total = 0;
        $num = 0;
        foreach($orders as $order){
            //判断待收货是否超时
            $id = DB::table('order_operations')
                  ->where(['order_after_id'   => $order->order_after_id,
                           'after_state'      => 5,
                           'over_after_state' => 6])
                  ->where('created_at', '<', $end_time)
                  ->value('id');
            if(!isset($id)) continue;
            $total++ ;

            $result  = self::aftermark_user_sign(['order_id'       => $order->order_id,
                                                  'user_id'        => $order->user_id,
                                                  'order_after_id' => $order->order_after_id,
                                                  'iden'           => 0,
                                                  'after_state'    => 6]);

            $num++ ;
        }
        Log::info('售后确认收货超时处理结果: 应提醒订单数--' . $total . ', 本次提醒订单数--' . $num);
        Log::info('----------售后确认收货超时处理结束----------');
        return true;
    }

    /**
        售后单确认收货处理
     */
    private static function aftermark_user_sign($input){
        /*
            1.修改售后单状态
            2.修改订单状态
            2.添加售后单状态变更记录
         */
        $after  = SQL::update(['table' => 'order_aftermarks',
                               'where' => ['order_after_id' => $input['order_after_id'],
                                           'state'          => 6],
                               'update'=> ['state'          => 7,
                                           'updated_at'     => time()]]);
        $order  = SQL::update(['table' => 'orders',
                               'where' => ['order_id'     => $input['order_id'],
                                           'state'        => 4,
                                           'is_aftermark' => 1],
                               'update'=> ['is_aftermark' => 0,
                                           'is_close'     => 1,
                                           'updated_at'   => time()]]);
        $operation = OrderTool::insert_order_operation(['order_id'         => $input['order_id'],
                                                        'iden'             => 0,
                                                        'user_id'          => '0',
                                                        'order_state'      => 4,
                                                        'over_order_state' => 4,
                                                        'after_state'      => 6,
                                                        'over_after_state' => 7,
                                                        'is_close'         => 1]);
        return true;
    }

}
